#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Build-in / Std

'''
Created on 2016年9月1日

@author: Hawk
'''
import sys
import wx
import MDIChildFrameBase
import BaseDialog
from model.Model import *
from action.Action import *
from ControlID import ControlID

class AddProductDialog(BaseDialog.BaseDialog):
    def __init__(self, *args, **kwds):
        BaseDialog.BaseDialog.__init__(
            self, None, -1, u'Add SKU',
            style=wx.CAPTION | wx.CLOSE_BOX,
            size=(400, 220))

        self.project_list = Project.select().where(Project.deleted == False)
        self.project_list_title = [pro.name for pro in self.project_list]
        self.label_project = wx.StaticText(self, -1, u"Project", pos=(20, 15))
        self.project_choice = wx.Choice(self, -1, pos=(80, 15), choices=self.project_list_title)
        #self.project_choice.Bind(wx.EVT_CHOICE, self.OnCategoryChoiceSelect)

        self.sku_list = Sku.select().where(Sku.deleted == False)
        self.sku_list_title = [s.name for s in self.sku_list]
        self.label_sku = wx.StaticText(self, -1, u"Sku", pos=(200, 15))
        self.sku_choice = wx.Choice(self, -1, pos=(260, 15), choices=self.sku_list_title)
        self.sku_choice.SetSize(self.project_choice.GetSize())
        #self.sku_choice.Bind(wx.EVT_CHOICE, self.OnCategoryChoiceSelect)

        self.label_owner = wx.StaticText(self, -1, u"Owner", pos=(20, 50))
        self.textctrl_owner = wx.TextCtrl(self, -1, size=(100, 20), pos=(80, 50))

        self.label_frm107_date = wx.StaticText(self, -1, u"FRM107", pos=(20, 85))
        self.frm107_date_ctrl = wx.DatePickerCtrl(self, -1, size=(100, 20), pos=(80, 85),
                                                  style=wx.DP_DROPDOWN)

        self.label_mp_date = wx.StaticText(self, -1, u"MP date", pos=(200, 85))
        self.mp_date_ctrl = wx.DatePickerCtrl(self, -1, size=(100, 20), pos=(260, 85),
                                                  style=wx.DP_DROPDOWN)
        #self.label_develop_mm = wx.StaticText(self, -1, u"Development MM", pos=(20, 120))
        #self.textctrl_develop_mm = wx.TextCtrl(self, -1, size=(100, 20), pos=(160, 120))

        #self.label_maintain_mm = wx.StaticText(self, -1, u"Maintain MM", pos=(20, 150))
        #self.textctrl_maintain_mm = wx.TextCtrl(self, -1, size=(100, 20), pos=(160, 150))

        self.label_comment = wx.StaticText(self, -1, u"Comment", pos=(20, 120))
        self.textctrl_comment = wx.TextCtrl(self, -1, size=(200, 20), pos=(80, 120))

        self.button_save = wx.Button(self, -1, u"Save", pos=(160, 150))
        self.Bind(wx.EVT_BUTTON, self.OnSaveButtonClicked, self.button_save)

    def OnCategoryChoiceSelect(self, event):
        #self.showMessageBox(self.category_choice.GetString(self.category_choice.GetSelection()))
        pass

    def OnSaveButtonClicked(self, event):
        project_name = self.project_choice.GetString(self.project_choice.GetSelection())
        selected_project = Project.getOne(Project.name == project_name)
        if selected_project is None:
            self.showMessageBox(u'选择Project')
            return

        sku_name = self.sku_choice.GetString(self.sku_choice.GetSelection())
        selected_sku = Sku.getOne(Sku.name == sku_name)
        if selected_sku is None:
            self.showMessageBox(u'选择SKU')
            return

        owner = self.getTextCtrlValueDefaultNone(self.textctrl_owner)

        frm107_date = datetime.datetime.strptime(self.frm107_date_ctrl.GetValue().Format("%Y-%m-%d"), "%Y-%m-%d").date() #20160907
        mp_date = datetime.datetime.strptime(self.mp_date_ctrl.GetValue().Format("%Y-%m-%d"), "%Y-%m-%d").date() #20160907

        comment = self.textctrl_comment.GetValue().strip()
        msg = Action().ProductMgr.add_product(selected_project.id, selected_sku.id,
                                              owner, frm107_date, mp_date, comment)
        if msg:
            self.EndModal(wx.ID_OK)
        else:
            self.showMessageBox(msg.message)

class ProductMgrFrame(MDIChildFrameBase.MDIChildFrameBase):
    menu_title_in_menubar = "&Product"

    def __init__(self, *args, **kwargs):
        MDIChildFrameBase.MDIChildFrameBase.__init__(self, *args, **kwargs)
        self.InitMenu()

        self.panel = wx.Panel(self)
        self.ListCtrl_ProductList = wx.ListCtrl(
            self.panel,
            - 1,
            style=wx.LC_REPORT)

        for col, text in enumerate([u'序号', u'id', u'Project', u'SKU',
                                     u'Owner', u'FRM107 date', u'MP date',
                                     u'开发MM', u'维护MM', u'备注']):
            self.ListCtrl_ProductList.InsertColumn(col, text)

        wx.EVT_LIST_ITEM_RIGHT_CLICK(
            self.ListCtrl_ProductList,
            - 1,
            self.OnProductListRightClick)

        self.InitData()

        self.sizer_left = wx.BoxSizer(wx.HORIZONTAL)
        self.sizer_left.Add(self.ListCtrl_ProductList, 1, wx.EXPAND | wx.ALL)
        self.panel.SetSizer(self.sizer_left)
        self.sizer_left.Fit(self)

    def InitData(self):
        self.product_list = Action().ProductMgr.get_products()
        self.ListCtrl_ProductList.DeleteAllItems()
        for idx, item in enumerate(self.product_list):
            index = self.ListCtrl_ProductList.InsertStringItem(sys.maxint, str(idx + 1))
            self.ListCtrl_ProductList.SetStringItem(index, 1, str(item.id))
            self.ListCtrl_ProductList.SetStringItem(index, 2, item.project.name)
            self.ListCtrl_ProductList.SetStringItem(index, 3, item.sku.name)
            self.ListCtrl_ProductList.SetStringItem(index, 4, item.owner)
            self.ListCtrl_ProductList.SetStringItem(index, 5, str(item.frm107_date))
            self.ListCtrl_ProductList.SetStringItem(index, 6, str(item.mp_date))
            self.ListCtrl_ProductList.SetStringItem(index, 7, str(item.development_mm))
            self.ListCtrl_ProductList.SetStringItem(index, 8, str(item.maintenance_mm))
            self.ListCtrl_ProductList.SetStringItem(index, 9, item.comment if item.comment is not None else u"")
        self.ListCtrl_ProductList.SetColumnWidth(0, 45)
        self.ListCtrl_ProductList.SetColumnWidth(1, 65)
        self.ListCtrl_ProductList.SetColumnWidth(2, 110)
        self.ListCtrl_ProductList.SetColumnWidth(3, 110)
        self.ListCtrl_ProductList.SetColumnWidth(4, 110)
        self.ListCtrl_ProductList.SetColumnWidth(5, 110)
        self.ListCtrl_ProductList.SetColumnWidth(6, 110)

    def InitMenu(self):
        self.menuBar_menubar_menu_items = [
            {'id': ControlID.MENUBAR_MENU_ITEM_PRODUCT_ADD, 'title': u'Add', 'separator': False, 'IsShown': lambda : True},
            {'id': ControlID.MENUBAR_MENU_ITEM_PRODUCT_REFRESH, 'title': u'Refresh', 'separator': False, 'IsShown': lambda : True,
                'hasSub': False,
                'sub' : [{'id': ControlID.MENUBAR_MENU_ITEM_CATEGORY_ADD, 'title': u"导出为CHM(UTF-8)"}]},
            ]
        self.menu = self.BuildMenuItems(self.menuBar_menubar_menu_items, self.OnMenubarMenu_Select)

    def OnMenubarMenu_Select(self, event, menu_item, path):
        id = event.GetId()
        if id == ControlID.MENUBAR_MENU_ITEM_PRODUCT_ADD:
            dlg = AddProductDialog()
            if wx.ID_OK == dlg.ShowModal():
                self.InitData()
            dlg.Destroy()
        elif id == ControlID.MENUBAR_MENU_ITEM_PRODUCT_REFRESH:
            self.InitData()

    def OnProductListRightClick(self, event):
        self.selected_row_index = event.GetText()

        self.sku_menu_itemms = [
            {'id': ControlID.SKU_LIST_MENU_VIEW, 'title': u"查看"},
            {'id': ControlID.SKU_LIST_MENU_DELETE, 'title': u"删除"}
            ]

        menu = self.BuildMenuItems(self.sku_menu_itemms, self.OnMenuSelect_SkuList)
        self.PopupMenu(menu, event.GetPoint())
        menu.Destroy()

    def OnMenuSelect_SkuList(self, event, menu_item, path):
        id = event.GetId()
        if id == ControlID.SKU_LIST_MENU_DELETE:
            self.selected_row_index = int(self.selected_row_index) - 1
            msg = Action().ProductMgr.del_product(self.product_list[self.selected_row_index].id)
            if msg:
                self.InitData()
            else:
                self.showMessageBox(msg.message)

    def OnActive(self):
        #print '%s has been actived' % self.GetTitle()
        parent_menubar = self.GetParent().GetMenuBar()
        pos = parent_menubar.FindMenu(self.menu_title_in_menubar)
        if pos == -1:
            parent_menubar.Insert(1, self.menu, self.menu_title_in_menubar)

    def OnDeactive(self):
        #print '%s has been deactived' % self.GetTitle()
        parent_menubar = self.GetParent().GetMenuBar()
        pos = parent_menubar.FindMenu(self.menu_title_in_menubar)
        if pos != -1:
            parent_menubar.Remove(pos)

